#include "loginwidget.h"
#include "ui_loginwidget.h"
#include <QMessageBox>
#include <QTimer>
#include <QSettings>

LoginWidget::LoginWidget(UserSession *session, QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::LoginWidget)
    , m_session(session)
{
    ui->setupUi(this);
    
    // 设置窗口属性
    setWindowTitle(tr("Audit Trail System - Login"));
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    
    // 连接信号槽
    connect(ui->loginButton, &QPushButton::clicked, this, &LoginWidget::onLoginClicked);
    connect(m_session, &UserSession::loginStatusChanged, 
            this, &LoginWidget::onSessionAboutToTimeout);
    
    // 加载保存的用户名
    QSettings settings;
    QString lastUser = settings.value("last_user").toString();
    if (!lastUser.isEmpty()) {
        ui->usernameInput->setText(lastUser);
        ui->passwordInput->setFocus();
    }
}

LoginWidget::~LoginWidget()
{
    delete ui;
}

void LoginWidget::onLoginClicked()
{
    if (ui->usernameInput->text().isEmpty()) {
        QMessageBox::warning(this, "错误", "用户名不能为空");
        ui->usernameInput->setFocus();
        return;
    }
    
    if (ui->passwordInput->text().isEmpty()) {
        QMessageBox::warning(this, "错误", "密码不能为空");
        ui->passwordInput->setFocus();
        return;
    }
    
    emit loginAttempt(ui->usernameInput->text(), ui->passwordInput->text());

    QString username = ui->usernameInput->text().trimmed();
    QString password = ui->passwordInput->text();
    
    if (m_session->authenticateUser(username, password)) {
        // 保存用户名
        QSettings settings;
        settings.setValue("last_user", username);
        
        accept();
    } else {
        QMessageBox::warning(this, tr("Login Failed"), 
                            tr("Invalid username or password. Please try again."));
        ui->passwordInput->clear();
        ui->passwordInput->setFocus();
    }
}

bool LoginWidget::validateInput()
{
    if (ui->usernameInput->text().isEmpty()) {
        QMessageBox::warning(this, "错误", "用户名不能为空");
        ui->usernameInput->setFocus();
        return false;
    }
    
    if (ui->passwordInput->text().isEmpty()) {
        QMessageBox::warning(this, "错误", "密码不能为空");
        ui->passwordInput->setFocus();
        return false;
    }
    
    return true;
}

void LoginWidget::onSessionAboutToTimeout()
{
    QMessageBox::warning(this, tr("Session Timeout"), 
                        tr("Your session status has changed. Please check your login status."));
}
